import { Input, Badge } from 'antd';
import React, { useState, useRef } from 'react';
import { PageContainer } from '@ant-design/pro-layout';
import ProTable from '@ant-design/pro-table';

import { queryRule, getMessage } from './service';

const TableList = () => {
  const [count, setCount] = useState();
  const [num, setNum] = useState();
  const actionRef = useRef();
  const handleGetMessage = () => {
    getMessage().then((res) => {
      if (res.code === 0) {
        setNum(res.data);
      }
    });
  };
  const columns = [
    {
      title: '发送手机号',
      dataIndex: 'mobile',
      render: (dom, entity) => {
        return <a>{dom}</a>;
      },
    },
    {
      title: '内容',
      dataIndex: 'content',
      hideInForm: true,
      hideInSearch: true,
    },
    {
      title: '状态',
      dataIndex: 'status',
      hideInForm: true,
      valueEnum: {
        1: {
          text: '失败',
          status: 'Default',
        },

        0: {
          text: '成功',
          status: 'Success',
        },
      },
    },
    {
      title: '发送时间',
      dataIndex: 'createTime',
      sorter: true,
      valueType: 'dateTime',
      hideInForm: true,
      renderFormItem: (item, { defaultRender, ...rest }, form) => {
        const status = form.getFieldValue('status');

        if (`${status}` === '0') {
          return false;
        }

        if (`${status}` === '3') {
          return <Input {...rest} placeholder="请输入异常原因！" />;
        }

        return defaultRender(item);
      },
    },
  ];
  return (
    <PageContainer>
      <div style={{ marginBottom: 10 }}>
        <div>
          短信平台短信剩余条数: &nbsp;
          <Badge status={num < 50000 ? 'processing' : 'success'} />
          {num}
        </div>
      </div>
      <ProTable
        headerTitle="发送记录"
        actionRef={actionRef}
        rowKey="id"
        bordered
        search={{
          labelWidth: 120,
        }}
        request={(params, sorter, filter) => queryRule({ ...params, sorter, filter })}
        postData={(payload) => {
          const { list, total } = payload;
          setCount(total);
          handleGetMessage();
          return list||[];
        }}
        pagination={{
          defaultPageSize: 30,
          showSizeChanger: false,
          showTitle: false,
          total: count,
          showTotal: (total) => `共${total}条`,
        }}
        columns={columns}
      />
    </PageContainer>
  );
};

export default TableList;
